<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2019/7/17
 * Time: 17:33
 */

namespace App\Model;

use App\Common\BaseComm;
use App\Enum\SysEnum;
use App\Utility\BaseEnum;
use App\Utility\RedisTools;

class GameRobot extends BaseModel
{
    public $tableName = 'qc_game_robots';
    public $userTableName = 'qc_user';
    protected $robotInitSetting = [
        'points' => 1000,
    ];

    public function __construct(){
        parent::__construct();
    }

    /**获取db的一行记录
     * @param $robotId
     * @return \EasySwoole\Mysqli\Mysqli|mixed|null
     * @throws \EasySwoole\Mysqli\Exceptions\ConnectFail
     * @throws \EasySwoole\Mysqli\Exceptions\PrepareQueryFail
     * @throws \Throwable
     */
    public function getDbRobotClient($robotId) {
        $result = $this->getDb()->where('robotId',$robotId)->getOne($this->tableName);
        return $result;
    }

    /**获取redis缓存的机器人客户端
     * @param $robotId
     * @return bool|\EasySwoole\Mysqli\Mysqli|mixed|null
     * @throws \EasySwoole\Mysqli\Exceptions\ConnectFail
     * @throws \EasySwoole\Mysqli\Exceptions\PrepareQueryFail
     * @throws \Throwable
     */
    public function getRedisRobotClient($robotId) {
        $robotClient = RedisTools::Pool_hGet(SysEnum::ROBOT_AGENTMD5_KEY,$robotId);
        if (empty($robotClient)){
            $field = ['agentId','robotName','md5Key'];
            $result = $this->getDb()->where('robotId',$robotId)->getOne($this->tableName,$field);
            if(isset($result) && !empty($result)){
                RedisTools::Pool_hSet(SysEnum::ROBOT_AGENTMD5_KEY,$robotId,json_encode($result));
                $robotClient = $result;
            }
        }else{
            $robotClient = json_decode($robotClient,true);
        }
        return $robotClient;
    }

    /**获取空闲的机器人
     * @param $robotId
     * @param int $uid
     * @return bool|\EasySwoole\Mysqli\Mysqli|mixed|null
     * @throws \EasySwoole\Mysqli\Exceptions\ConnectFail
     * @throws \EasySwoole\Mysqli\Exceptions\PrepareQueryFail
     * @throws \Throwable
     */
    public function getFreeUser($robotId,&$uid=0) {
        $robotClient = $this->getRedisRobotClient($robotId);
        if(!empty($robotClient)){
            $agentId = $robotClient['agentId'] ?? 0;
            if ($agentId<=0 || empty($agentId)){
                return false;
            }
            //代理下的所有机器人
            $users = $this->getDb()->where('isNation',3)->where('recUid',$agentId)->where('status',1)->getColumn($this->userTableName,'uid');
            BaseEnum::Logger('代理下所有机器人 GameRobot->getFreeUser--->>>' .json_encode($users), 'user-login');
            if (empty($users)){
                return false;
            }
            $offUids = [];
            foreach ($users as $key => $val){
                //哪一些是离线的
                $status = RedisTools::Pool_hGet(SysEnum::ROBOT_ONLINEPLAYER_KEY,$val);
                if ($status == 2){
                    $offUids[] = $val;
                    break;
                }elseif($status == 1){
                    //剔除在线
                    unset($users[$key]);
                }
            }

            if (!empty($offUids)){
                $key = array_rand($offUids,1);
                $uid = $offUids[$key];
                BaseEnum::Logger('缓存内空闲机器人 GameRobot->getFreeUser--->>>' .json_encode($offUids), 'user-login');
            }elseif(!empty($users)){
                $key = array_rand($users,1);
                $uid = $users[$key];
                BaseEnum::Logger('数据库内空闲机器人 GameRobot->getFreeUser--->>>' .json_encode($users), 'user-login');
            }
            if ($uid>0){
                $user = new User();
                $freeUser = $user->getUserByUid($uid);
                return $freeUser;
            }
        }
        return false;
    }

    /**生成机器人信息
     * @param $robotId
     * @param int $uid
     * @return bool|\EasySwoole\Mysqli\Mysqli|mixed|null
     * @throws \EasySwoole\Mysqli\Exceptions\ConnectFail
     * @throws \EasySwoole\Mysqli\Exceptions\PrepareQueryFail
     * @throws \Throwable
     */
    public function createRobotUser($robotId,&$uid=0)
    {
        $robotClient = $this->getDbRobotClient($robotId);
        if (!empty($robotClient)){
            $agentId = $robotClient['agentId'] ?? 0;
            $maxNums = $robotClient['maxNums'] ?? 0;
            $createdNums = $robotClient['createdNums'] ?? 0;
            //达到最大值后无法创建新的机器人
            if($agentId<=0 || $maxNums<=0 || $createdNums>=$maxNums){
                return false;
            }
            $userModel = new User();
            $agent = $userModel->getAgentById($agentId,['name','ancestor_ids']);
            $name = $agentId.'_r'.str_pad($createdNums+1,strlen(strval($maxNums)),'0',STR_PAD_LEFT);
            $recUser = $agent['name'];
            $ancestor_ids = empty($agent['ancestor_ids']) ? $agentId : $agent['ancestor_ids'].','.$agentId;
            $points = $this->robotInitSetting['points'] ?? 0;
            $reg_ip = BaseComm::getRealClientIP();
            //非空字段
            $data = [
                'name' => $name,
                'password' => '8677D2D15C655180174AA354B897FCA9',
                'group_id' => 1,
                'status' => 1,
                'recUid' => $agentId,
                'recUser' => $recUser,
                //'agencyOdds',
                'ancestor_ids' => $ancestor_ids,
                'level' => 1,
                //'grow_score',
                'points' => $points,
                'isNation' => 3,
                //'cashPwd',
                //'realname',
                //'invitation_code',
                'reg_time' => time(),
                'reg_ip' => $reg_ip,
                //'login_time',
                //'login_ip',
                //'login_num',
                //'set_password_time',
                //'set_cashPwd_time',
                //'update_time',
                //'withdraw_limit',
                //'agentPoints',
                //'totalUsedPoints',
                //'totalWithPoints',
                //'totalChildPoints',
                //'email',
                //'weixin',

                //'nickName',
                //'birthday',
                'gender' => array_rand([0,1,2],1),
                'head_url' => array_rand([0,1,2,3,4,5,6,7]),
                'user_ident' => 1,
                'desc_key' => 'ABC1232134123SEE',
                'md5_key' => 'MYM23456',
                //'domain'
            ];
            $uid = $this->getDb()->insert($this->userTableName,$data);
            if ($uid > 0){
                BaseEnum::Logger('机器人信息插入表 GameRobot->createRobotUser--->>>' . json_encode($data), 'user-login');
                $res = $this->getDb()->where('robotId',$robotId)->setInc($this->tableName,'createdNums',1);
                $user = $userModel->getUserByUid($uid);
                return $user;
            }
        }

        return false;
    }


}